package com.linjian.togetherbirthday.fragment;

import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.jcodecraeer.xrecyclerview.ProgressStyle;
import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.linjian.togetherbirthday.MainActivity;
import com.linjian.togetherbirthday.R;
import com.linjian.togetherbirthday.adapter.base.recyler.ItemWrapper;
import com.linjian.togetherbirthday.adapter.base.recyler.RecyclerAdapter;
import com.linjian.togetherbirthday.adapter.base.recyler.RecyclerHolder;
import com.linjian.togetherbirthday.base.BaseFragment;
import com.linjian.togetherbirthday.bean.FoundDynamicBean;
import com.linjian.togetherbirthday.contant.HttpContant;
import com.linjian.togetherbirthday.util.LogUtil;
import com.linjian.togetherbirthday.utils.HttpUtils;
import com.linjian.togetherbirthday.utils.NoticeEvent;
import com.linjian.togetherbirthday.utils.SharedPreferencesUtil;
import com.sdsmdg.tastytoast.TastyToast;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class HomeTwoFragment extends BaseFragment implements View.OnClickListener, XRecyclerView.LoadingListener {

    private RelativeLayout foodRl,movieRl;
    private ImageView backIv;
    private TextView titleTv,rightTv;

    private MainActivity activity;

    private XRecyclerView mRecyclerView;
    private RecyclerAdapter<FoundDynamicBean.DataBean> mRecylerAdapter;
    private List<FoundDynamicBean.DataBean> mList;
    private View mView;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        EventBus.getDefault().register(this);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            getActivity().getWindow().getDecorView().setSystemUiVisibility( View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN|View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR);
        }
    }

    public static HomeTwoFragment newInstance() {
        HomeTwoFragment homeOneFragment = new HomeTwoFragment();
        Bundle bundle = new Bundle();
//        bundle.putInt(Integer.class.getName(), resId);
        homeOneFragment.setArguments(bundle);
        return homeOneFragment;
    }

    @Override
    protected int setView() {
        return R.layout.fragment_home_two;
    }

    @Override
    protected void init(View view) {
        activity = (MainActivity) getActivity();

        backIv = view.findViewById(R.id.layout_head_back_iv);
        titleTv = view.findViewById(R.id.layout_head_title_tv);
        rightTv = view.findViewById(R.id.layout_head_right_tv);

        foodRl = view.findViewById(R.id.share_food_rl);
        movieRl = view.findViewById(R.id.share_movie_rl);
        mRecyclerView = view.findViewById(R.id.found_recyler);

        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(layoutManager);

        mRecyclerView.setRefreshProgressStyle(ProgressStyle.BallSpinFadeLoader);
        mRecyclerView.setLoadingMoreProgressStyle(ProgressStyle.BallRotate);
        mRecyclerView.setArrowImageView(R.mipmap.iconfont_downgrey);

        mRecyclerView
                .getDefaultRefreshHeaderView()
                .setRefreshTimeVisible(true);
        mRecyclerView.getDefaultFootView().setLoadingHint("自定义加载中提示");
        mRecyclerView.getDefaultFootView().setNoMoreHint("自定义加载完毕提示");
        mRecyclerView.setLimitNumberToCallLoadMore(1);
        mRecyclerView.setLoadingListener(this);

        mRecylerAdapter = new RecyclerAdapter<FoundDynamicBean.DataBean>(mItemListener) {
            @Override
            public ItemWrapper getItemHolder(int position) {
                return new ItemWrapper(R.layout.item_dynamic,HomeTwoAdapter.class);
            }
        };
        mRecyclerView.setAdapter(mRecylerAdapter);

    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        backIv.setVisibility(View.GONE);
        rightTv.setVisibility(View.GONE);
        titleTv.setText("发现");
        setListener();
        homeActivity(1);
    }
    private void setListener() {
        foodRl.setOnClickListener(this);
        movieRl.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.share_food_rl:
                activity.replaceFragment("FoodFragment","");
                break;
            case R.id.share_movie_rl:
                activity.replaceFragment("MovieListFragment","");
                break;
        }
    }

    private OnItemListener mItemListener = new OnItemListener() {
        @Override
        public void onItemClick(View view, int position) {

        }
    };


    FoundDynamicBean foundDynamicBean;

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMsg(NoticeEvent event){
        switch (event.getCls()){
            case "requestFail":
                TastyToast.makeText(getActivity(),"请求失败",TastyToast.LENGTH_SHORT,TastyToast.ERROR).show();
                break;
            case "FoundDynamic":
                LogUtil.e("FoundDynamic",event.getData().toString());
                try {
                    JSONObject object = new JSONObject(event.getData().toString());
                    if (object.getInt("code") == 200){
                        mList = new ArrayList<>();
                        foundDynamicBean = new Gson().fromJson(event.getData().toString(),FoundDynamicBean.class);
                        mList.addAll(foundDynamicBean.getData());
                        mRecylerAdapter.addAll(mList);
                        mRecylerAdapter.notifyDataSetChanged();
                    }else {
                        TastyToast.makeText(getActivity(),object.getString("msg"),TastyToast.LENGTH_SHORT,TastyToast.ERROR).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                break;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        if(mRecyclerView != null){
            mRecyclerView.destroy();
            mRecyclerView = null;
        }
    }


    /**
     * 请求首页活动
     */
    private void homeActivity(int currentPage){

        HttpUtils.doGet(HttpContant.URL + HttpContant.QueryMealEssay+"?currentPage="+currentPage
                , "SESSION=" + String.valueOf(SharedPreferencesUtil.get(getActivity(), "Cookie", ""))
                , new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        EventBus.getDefault().post(new NoticeEvent("requestFail"));
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        EventBus.getDefault().post(new NoticeEvent("FoundDynamic",response.body().string()));
                    }
                });
    }

    @Override
    public void onRefresh() {

    }

    @Override
    public void onLoadMore() {

    }

    interface OnItemListener {
        void onItemClick(View view, int position);
    }



    static class HomeTwoAdapter extends RecyclerHolder<FoundDynamicBean.DataBean> {

        private TextView releaseTimeTv,nameTv,yearTv,contantTv,addressTv,browseTv,commentsTv,giveLikeTv;
        private ImageView userIv;
        private OnItemListener mItemListener;

        public HomeTwoAdapter(View itemView, OnItemListener listener) {
            super(itemView);
            userIv = itemView.findViewById(R.id.item_user_iv);
            releaseTimeTv = itemView.findViewById(R.id.item_release_time);
            nameTv = itemView.findViewById(R.id.item_user_name);
            yearTv = itemView.findViewById(R.id.item_dynamic_user_year);
            contantTv = itemView.findViewById(R.id.item_dynamic_contant);
            addressTv = itemView.findViewById(R.id.item_dynamic_address);
            browseTv = itemView.findViewById(R.id.item_dynamic_browse_num);
            commentsTv = itemView.findViewById(R.id.item_dynamic_comments_num);
            giveLikeTv = itemView.findViewById(R.id.item_dynamic_give_like_num);

            mItemListener = listener;
        }

        @Override
        public void onBindView(FoundDynamicBean.DataBean dataBean) {
            Log.i("111111",dataBean.getEssaytime());
            releaseTimeTv.setText(dataBean.getEssaytime().split("T")[0]+"  "+dataBean.getEssaytime().split("T")[1].split(":")[0]+":"+dataBean.getEssaytime().split("T")[1].split(":")[1]);
            nameTv.setText(dataBean.getNickname());
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy");
            int year = Integer.valueOf(dataBean.getBirthday().split("-")[0]);
            int newYear = Integer.valueOf(simpleDateFormat.format(new Date()));
            if (dataBean.getSex() == 1) {
                yearTv.setCompoundDrawablesRelativeWithIntrinsicBounds(yearTv.getContext().getResources().getDrawable(R.mipmap.nan_icon), null, null, null);
            } else {
                yearTv.setCompoundDrawablesRelativeWithIntrinsicBounds(yearTv.getContext().getResources().getDrawable(R.mipmap.nv_icon), null, null, null);
            }
            yearTv.setText((newYear - year) + "");
            contantTv.setText(dataBean.getEssay());
            addressTv.setText(dataBean.getPlacename());
            commentsTv.setText("111人");
            giveLikeTv.setText("111人");
            Glide.with(userIv.getContext()).load(dataBean.getHeadimg()).asBitmap().error(R.mipmap.user_pic).placeholder(R.mipmap.user_pic).into(userIv);
        }
    }

}
